package com.kingint.web.util.handle;


import com.kingint.common.unitedresult.K;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * 全局异常统一处理
 */
@ControllerAdvice
public class GlobalExceptionHandler extends SimpleMappingExceptionResolver {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    public static final String DEFAULT_ERROR_VIEW = "error";


    @ExceptionHandler({BindException.class})
    @ResponseBody
    public Object validExceptionHandler(BindException e) {
        e.printStackTrace();
        K.error().data(e.getFieldError().getDefaultMessage());
        return  K.error().data(e.getFieldError().getDefaultMessage());
    }


    @ExceptionHandler({Exception.class})
    @ResponseBody
    public Object jsonExceptionHandler(HttpServletRequest req, Exception e) {
        log.error("系统出错", e);
        return K.error().data("系统出错");
    }

    /**
     * 功能描述: @Validated 校验失败时的异常，将校验结果以json格式返回
     * @author wangwren
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        BindingResult bindingResult = ex.getBindingResult();
        StringBuilder sb = new StringBuilder();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        for (FieldError fieldError : fieldErrors){
            sb.append(fieldError.getDefaultMessage()).append(",");
        }
        sb.deleteCharAt(sb.lastIndexOf(","));
        return K.error().data(sb.toString());
    }
}